package main

import (
	"fmt"
	"io"
	"net/http"
	"net/rpc"
	"net/rpc/jsonrpc"
	"strconv"

	"gitee.com/lcc_dr/rpc/pbrpc/pb"
	"gitee.com/lcc_dr/rpc/pbrpc/service"
)

/*
1、自定义一个函数
2、注册到rpc
3、rpc 启动

127.0.0.1:1234/rpc_http
{
    "method":"HelloService.Hello",
    "params":[{"Value":"lcc"}],
    "id":2
}

*/
var _ service.HelloService = (*HelloService)(nil)

type HelloService struct{}

func (h *HelloService) Hello(res *pb.Request, response *pb.Response) error {
	fmt.Println(res.Value)
	response.Value = "hello " + res.Value
	return nil
}

func (h *HelloService) Calc(res *service.Calc, response *int) error {
	*response = res.A * res.B
	return nil
}

func (h *HelloService) Stu(res *pb.Student, response *pb.Response) error {
	fmt.Printf("wuhan different name is %s, age is %d", res.Name, res.Age)
	response.Value = "hubei" + strconv.Itoa(int(res.Age))
	return nil
}

/*
{
    "method":"HelloService.Stu",
    "params":[{"name":"lcc","age":23}],
    "id":2
}
*/

func NewRpcWriteReadClosdHttp(w http.ResponseWriter, r *http.Request) *RpcWriteReadClose {

	return &RpcWriteReadClose{w, r.Body}
}

type RpcWriteReadClose struct {
	io.Writer
	io.ReadCloser
}

func main() {

	rpc.RegisterName(service.SERVICE_NAME, &HelloService{})
	http.HandleFunc("/rpc_http", func(w http.ResponseWriter, r *http.Request) {

		conn := NewRpcWriteReadClosdHttp(w, r)
		rpc.ServeRequest(jsonrpc.NewServerCodec(conn))

	})
	http.ListenAndServe(":1234", nil)

}
